<template>
  <div>
    <div class="ef-node-form">
      <div class="ef-node-form-header">
        编辑
      </div>
      <div class="ef-node-form-body">

        <el-form
          v-show="type === 'node'"
          ref="dataForm"
          :model="node"
          label-width="80px"
        >

          <el-form-item label="类型">
            <el-input
              v-model="node.type"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="node.name" />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-check"
              @click="save"
            >保存</el-button>
          </el-form-item>
        </el-form>
        <el-form
          v-show="type === 'line'"
          ref="dataForm"
          :model="line"
          label-width="80px"
        >
          <el-form-item label="条件">
            <el-input v-model="line.label" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-close">重置</el-button>
            <el-button
              type="primary"
              icon="el-icon-check"
              @click="saveLine"
            >保存</el-button>
          </el-form-item>
        </el-form>

        <!-- 表 -->
        <template v-if="node.type ==='table'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="30%"
          >
            <el-form
              v-show="node.type === 'table'"
              ref="dataForm"
              :model="node.data"
              label-width="80px"
              :rules="rules"
            >
              <el-form-item label="任务id" prop="taskId" label-width="120px">
                <el-input v-model="node.data.taskId" :disabled="true" />
              </el-form-item>
              <el-form-item label="数据库id" prop="databaseId" label-width="120px">
                <el-input v-model="node.data.databaseId" :disabled="true" />
              </el-form-item>
              <el-form-item label="数据表" label-width="120px">
                <SelectTree
                  v-if="node.data.show1"
                  placeholder="请选择父级id"
                  :options="node.data.selectId"
                  :props="props"
                  :value=" node.data.databaseId ? node.data.treeId + '' : '' "
                  @getValue="getValue"
                />
              </el-form-item>
              <el-form-item label="表别名" prop="tableAsName" label-width="120px">
                <el-input v-model="node.data.tableAsName" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="determine('show2',node)">下一步</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>

          <template v-if="node.data.show2">
            <el-dialog
              title="字段"
              :visible.sync="node.data.show2"
              width="70%"
            >
              <el-table
                ref="multipleTable"
                v-loading="loading"
                :data="node.data.tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55"
                />
                <el-table-column
                  prop="field"
                  label="字段"
                />
                <el-table-column
                  prop="fieldType"
                  label="类型/长度"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="isNull"
                  label="非空"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="comment"
                  label="注释"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="处理规则"
                >
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.fieldAsEngineId" placeholder="请选择">
                      <el-option
                        v-for="item in node.data.select"
                        :key="item.id"
                        :label="item.engineName"
                        :value="item.id"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="表别名"
                  width="260"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.tableAsField" />
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" @click="determine('show1',node)">上一步</el-button>
              <el-button type="primary" @click="determine('ok',node)">完成</el-button>
            </el-dialog>
          </template>

        </template>

        <!-- excel -->
        <template v-if="node.type ==='excel'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <excel />
          </el-dialog>
        </template>

        <!-- 联查 -->
        <template v-if="node.type ==='join'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <el-form ref="dataForm" :model="node.data" :rules="rules" label-width="120px">
              <el-form-item label="节点1明细">
                {{ '数据库:' + node.data.fromNodeData[0].data.tableName }}
                {{ '别名:' + node.data.fromNodeData[0].data.tableAsName }}
              </el-form-item>
              <el-form-item label="节点2明细">
                {{ '数据库:' + node.data.fromNodeData[1].data.tableName }}
                {{ '别名:' + node.data.fromNodeData[1].data.tableAsName }}
              </el-form-item>
              <el-form-item label="联查方式">
                <el-select v-model="node.data.joinType" placeholder="请选择">
                  <el-option
                    v-for="item in joinTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="关联字段">
                <span>
                  <el-select v-model="node.data.leftJoinField" placeholder="请选择">
                    <el-option
                      v-for="item in node.data.fromNodeData[0].data.multipleSelection"
                      :key="item.field"
                      :label="item.tableAsField"
                      :value="item.field"
                    />
                  </el-select>
                </span>
                <span>
                  <el-select v-model="node.data.rightJoinField" placeholder="请选择">
                    <el-option
                      v-for="item in node.data.fromNodeData[1].data.multipleSelection"
                      :key="item.field"
                      :label="item.tableAsField"
                      :value="item.field"
                    />
                  </el-select>
                </span>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('ok',node)">保存并返回</el-button>
              <el-button @click="determine('show3',node)">取 消</el-button>
            </div>
          </el-dialog>
        </template>

        <!-- 分组 -->
        <template v-if="node.type ==='group'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <el-form ref="dataForm" :model="node.data" :rules="rules" label-width="120px">
              <el-form-item label="选择的节点id">
                {{ node.data.nodeId[node.data.selectTableName] }}
              </el-form-item>
              <el-form-item label="选择表">
                <el-select v-model="node.data.selectTableName" placeholder="请选择" @change="selectChange">
                  <el-option
                    v-for="item in node.data.tableFrom"
                    :key="item.value"
                    :label="item.tableName"
                    :value="item.tableName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择字段">
                <el-select v-model="node.data.selectTableField" placeholder="请选择">
                  <el-option
                    v-for="item in node.data.fieldData[node.data.selectTableName]"
                    :key="item.field"
                    :label="item.tableAsField"
                    :value="item.field"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('ok',node)">保存并返回</el-button>
              <el-button @click="determine('show3',node)">取 消</el-button>
            </div>
          </el-dialog>
        </template>

        <!-- 排序 -->
        <template v-if="node.type ==='order'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <el-form ref="dataForm" :model="node.data" :rules="rules" label-width="120px">
              <el-form-item label="选择的节点id">
                {{ node.data.nodeId[node.data.selectTableName] }}
              </el-form-item>
              <el-form-item label="选择表">
                <el-select v-model="node.data.selectTableName" placeholder="请选择" @change="selectChange">
                  <el-option
                    v-for="item in node.data.tableFrom"
                    :key="item.value"
                    :label="item.tableName"
                    :value="item.tableName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择字段">
                <el-select v-model="node.data.selectTableField" placeholder="请选择">
                  <el-option
                    v-for="item in node.data.fieldData[node.data.selectTableName]"
                    :key="item.field"
                    :label="item.tableAsField"
                    :value="item.field"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="排序方式">
                <el-select v-model="node.data.sort" placeholder="请选择">
                  <el-option
                    v-for="item in sortOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('ok',node)">保存并返回</el-button>
              <el-button @click="determine('show3',node)">取 消</el-button>
            </div>
          </el-dialog>
        </template>

        <!-- 数据引擎 -->
        <template v-if="node.type ==='logic'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <el-form ref="dataForm" :model="node.data" :rules="rules" label-width="120px">
              <el-form-item label="选择的节点id">
                {{ node.data.nodeId[node.data.selectNodeTable] }}
              </el-form-item>
              <el-form-item label="选择表">
                <el-select v-model="node.data.selectNodeTable" placeholder="请选择" @change="selectChange">
                  <el-option
                    v-for="item in node.data.tableFrom"
                    :key="item.value"
                    :label="item.tableName"
                    :value="item.tableName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择字段">
                <el-select v-model="node.data.selectNodeField" placeholder="请选择">
                  <el-option
                    v-for="item in node.data.fieldData[node.data.selectNodeTable]"
                    :key="item.field"
                    :label="item.tableAsField"
                    :value="item.field"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="规则引擎">
                <el-select v-model="node.data.fieldEngin" placeholder="请选择">
                  <el-option
                    v-for="item in node.data.fieldEnginOptions"
                    :key="item.id"
                    :label="item.engineName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('ok',node)">保存并返回</el-button>
              <el-button @click="determine('show3',node)">取 消</el-button>
            </div>
          </el-dialog>
        </template>

        <!-- 数据输出 -->
        <template v-if="node.type ==='output'">
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show1"
            width="80%"
          >
            <el-table
              ref="multipleTable"
              :data="node.data.fieldData"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column
                prop="field"
                label="字段"
                width="120"
              />
              <el-table-column
                prop="tableAsField"
                label="别名"
                show-overflow-tooltip
              />
              <el-table-column
                prop="isNull"
                label="非空"
                show-overflow-tooltip
              />
              <el-table-column
                prop="comment"
                label="注释"
                show-overflow-tooltip
              />
            </el-table>
            <div>
              <span v-for="(item,index) in multipleSelection" :key="index">
                <el-tag style="margin:5px">
                  {{ item.field }}
                </el-tag>
              </span>
            </div>
            <el-form
              v-show="type === 'node'"
              ref="dataForm"
              :model="node"
              label-width="80px"
              :rules="rules"
            >
              <el-form-item label="数据表" label-width="120px">
                <SelectTree
                  placeholder="请选择父级id"
                  :options="node.data.selectId"
                  :props="props"
                  :value=" node.data.databaseId ? node.data.treeId + '' : '' "
                  @getValue="getValue"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('show2',node)">下一步</el-button>
            </div>
          </el-dialog>
          <el-dialog
            :title="node.name"
            :visible.sync="node.data.show2"
            width="80%"
          >
            <el-table
              v-loading="loading"
              :data="node.data.multipleSelection"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column
                label="输入字段"
              >
                <template slot-scope="scope">
                  {{ scope.row.tableAsField }}
                </template>
              </el-table-column>
              <el-table-column
                prop="columnName"
                label="目标字段"
              >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.toTableAsField" placeholder="请选择">
                    <el-option
                      v-for="item in node.data.tableData"
                      :key="item.field"
                      :label="item.field"
                      :value="item.field"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine('show1',node)">上一步</el-button>
              <el-button type="primary" @click="determine('ok',node)">完成</el-button>
            </div>
          </el-dialog>
        </template>
      </div>
      <!--<div class="el-node-form-tag"></div>-->
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import SelectTree from '@/components/TreeSelect'
import { apiGetList, apiDatasourceInfoTables } from '@/api/dataAnalysis/index'
import { listEngine } from '@/api/engine/index'
import excel from '@/views/xlsx/index'

export default {
  components: {
    SelectTree,
    excel
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      visible: true,
      // node 或 line
      type: 'node',
      node: {},
      line: {},
      data: {},
      // 校验
      rules: {
        taskId: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        databaseId: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        tableAsName: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      // table 树状
      props: { // 配置项（必选）
        value: 'id',
        label: 'label',
        children: 'children'
        // disabled:true
      },
      // 测试下拉
      options: [{
        value: '1',
        label: '黄金糕'
      }, {
        value: '2',
        label: '双皮奶'
      }],
      // 测试表格
      tableData: [{
        date: '2016-05-03'
      }, {
        date: '2016-05-02'
      }, {
        date: '2016-05-04'
      }, {
        date: '2016-05-01'
      }, {
        date: '2016-05-08'
      }, {
        date: '2016-05-06'
      }, {
        date: '2016-05-07'
      }],
      // 表格多选
      multipleSelection: [],
      // 联查选择
      joinTypeOptions: [{
        value: 'left',
        label: '左联查'
      }, {
        value: 'right',
        label: '右联查'
      }, {
        value: 'inner',
        label: '内联查'
      }],
      // 排序方式
      sortOptions: [{
        value: 'DES',
        label: '升序'
      }, {
        value: 'DESC',
        label: '降序'
      }]
    }
  },
  created() {
  },
  methods: {
    /**
     * 修改，这里可以根据传入的ID进行业务信息获取
     * @param data
     * @param id
     */
    nodeInit(data, id) {
      this.data = data
      this.node = []
      console.log(this.data, this.node, '开始')
      data.nodeList.filter((node) => {
        if (node.id === id) {
          this.node = cloneDeep(node)
          console.log(this.node, this.node.type)
          // 表的处理
          if (this.node.type === 'table') {
            if (this.node.data.selectId.length === 0) {
              // 表数据库选择
              apiGetList().then(res => {
                res.data.forEach(item => {
                  item.children = []
                  item.label = item.name
                })
                this.node.data.selectId = res.data
              })
            }
          } else if (this.node.type === 'join') {
            // 联查处理
            console.log(data, '联查', node.id)
            const lineFrom = []
            // 找到关联线的上级
            data.lineList.filter((line) => {
              if (line.to === node.id) {
                lineFrom.push(line.from)
              }
            })
            // 获取到上级的data
            const fromNodeData = []
            data.nodeList.filter((node) => {
              if (lineFrom.indexOf(node.id) > -1) {
                fromNodeData.push(node)
              }
            })
            this.node.data.fromNodeData = fromNodeData
            this.node.data.leftId = fromNodeData[0].id
            this.node.data.rightId = fromNodeData[1].id
            console.log(fromNodeData, '关联上级')
          } else if (this.node.type === 'group' || this.node.type === 'order') {
            // 处理分组 || 处理排序
            const tableFrom = [] // 数据表
            const fieldData = {} // 数据表,对应字段
            const nodeId = {} // 表对应node id
            // 获取所有的表
            data.nodeList.filter((node) => {
              if (node.type === 'table') {
                tableFrom.push(node.data)
                fieldData[node.data.tableName] = node.data.multipleSelection
                nodeId[node.data.tableName] = node.id
              }
            })
            this.node.data.tableFrom = tableFrom
            this.node.data.fieldData = fieldData
            this.node.data.nodeId = nodeId
          } else if (this.node.type === 'logic') {
            // 处理引擎
            // 获取规则select
            listEngine({
              pageNum: 1,
              pageSize: 1000,
              codeType: 'java'
            }).then((res) => {
              res.rows.unshift({
                engineName: '无规则',
                id: 'noSelectLogic'
              })
              this.node.data.fieldEnginOptions = res.rows
            })

            const tableFrom = [] // 数据表
            const fieldData = {} // 数据表,对应字段
            const nodeId = {} // 表对应node id
            // 获取所有的表
            data.nodeList.filter((node) => {
              if (node.type === 'table') {
                tableFrom.push(node.data)
                fieldData[node.data.tableName] = node.data.multipleSelection
                nodeId[node.data.tableName] = node.id
              }
            })
            this.node.data.tableFrom = tableFrom
            this.node.data.fieldData = fieldData
            this.node.data.nodeId = nodeId
          } else if (this.node.type === 'output') {
            this.multipleSelection = []
            // 数据输出
            if (this.node.data.selectId.length === 0) {
              // 表数据库选择
              apiGetList().then(res => {
                res.data.forEach(item => {
                  item.children = []
                  item.label = item.name
                })
                this.node.data.selectId = res.data
              })
              const fieldData = [] // 数据表,对应字段
              // 获取所有的表
              data.nodeList.filter((node) => {
                if (node.type === 'table') {
                  node.data.multipleSelection.filter(item => {
                    fieldData.push(item)
                  })
                }
              })
              this.node.data.fieldData = fieldData
            } else {
              // 解决dom异步更新
              this.$nextTick(() => {
                console.log(this.node.data)
                // 默认选中 fieldData列表,multipleSelection选中data
                this.node.data.fieldData.forEach(row => {
                  node.data.multipleSelection.forEach(row2 => {
                    if (row2.tableAsField === row.tableAsField) {
                      this.$refs.multipleTable.toggleRowSelection(row, true)
                    }
                  })
                })
              })
            }
          }
        }
      })
    },
    lineInit(line) {
      this.type = 'line'
      this.line = line
    },
    // 修改连线
    saveLine() {
      this.$emit('setLineLabel', this.line.from, this.line.to, this.line.label)
    },
    save() {
      this.data.nodeList.filter((node) => {
        if (node.id === this.node.id) {
          node.name = this.node.name
          node.left = this.node.left
          node.top = this.node.top
          node.ico = this.node.ico
          node.data = this.node.data
          console.log(node, '回显')
          this.$emit('repaintEverything')
        }
      })
    },
    // 确定
    determine(show, data) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(show, data)
          const nodeData = data.data

          // 弹窗切换
          if (show === 'show2') {
            nodeData.show2 = true
            // 存储选中项
            if (data.type === 'output') {
              nodeData.multipleSelection = this.multipleSelection
            }
          } else if (show === 'show1') {
            nodeData.show1 = true
            nodeData.show2 = false
          } else if (show === 'show3') {
            nodeData.show1 = false
          } else {
          // 结束保存
            nodeData.show1 = false
            nodeData.show2 = false
            if (show === 'ok' && data.type === 'table') {
              // 存储选中项
              nodeData.multipleSelection = this.multipleSelection
              this.save()
            } else {
              this.save()
            }
          }

          // 展示,请求区分
          if (data.type === 'table' && show === 'show2') {
            if (!nodeData.tableData) {
              // 清空选中
              this.multipleSelection = []
              // 选中标注
              nodeData.multipleSelection = []
              this.loading = true
              this.$set(nodeData, 'tableData', [])
              // 获取talbe 表格
              apiDatasourceInfoTables(nodeData.databaseId, nodeData.tableName).then((res) => {
                res.data.forEach(item => {
                  item.fieldAsEngineId = 'noSelectLogic'
                  item.tableAsField = `${nodeData.tableAsName}_${item.field}`
                })
                this.loading = false
                this.$set(nodeData, 'tableData', res.data)
              })
              // 获取规则select
              listEngine({
                pageNum: 1,
                pageSize: 1000,
                codeType: 'sql'
              }).then((res) => {
                res.rows.unshift({
                  engineName: '无规则',
                  id: 'noSelectLogic'
                })
                this.$set(nodeData, 'select', res.rows)
              })
            } else if (data.type === 'table') {
              // 解决dom异步更新
              this.$nextTick(() => {
                // 默认选中 tableData列表,multipleSelection选中data
                nodeData.tableData.forEach(row => {
                  nodeData.multipleSelection.forEach(row2 => {
                    if (row2.field === row.field) {
                      this.$refs.multipleTable.toggleRowSelection(row, true)
                    }
                  })
                })
              })
            }
          }

          // 数据输出
          if (data.type === 'output' && show === 'show2') {
            // 获取talbe 表格
            apiDatasourceInfoTables(nodeData.databaseId, nodeData.tableName).then((res) => {
              res.data.forEach(item => {
                item.toTableAsField = `${nodeData.tableAsName}_${item.field}`
              })
              this.loading = false
              this.$set(nodeData, 'tableData', res.data)
            })
            // if (!nodeData.tableData.length) {
            //   console.log('aa')
            // } else {
            //   console.log('aa')
            // }
          }
        }
      })
    },
    // selectTree,选择的id
    getValue(id, e, ref) {
      console.log(id, e, this.node.data, 'aa')
      // 点击表结束
      // if (!id || e.end) {

      // }
      // 点击表,查字段
      if (e && e.table) {
        console.log('aa', e.table)
        this.node.data.databaseId = e.baseId
        this.node.data.tableName = e.name
        this.node.data.treeId = e.id
        return false
      } else if (id && e.id) {
        // 点击选中条件,库
        // ref.$children[0].$el.classList.remove('el-tree-node__label')
        // 查表，库已经确定
        apiDatasourceInfoTables(e.id).then(response => {
          const data = []
          response.data.forEach((item, index) => {
            data.push({
              baseId: e.id,
              name: item.tableName,
              label: item.tableName + '-' + item.tableComment,
              id: (new Date()).valueOf() + index,
              table: true
            })
          })
          e.children = data
          this.node.nodeId = null
        })
      }
    },
    handleSelectionChange(val) {
      if (this.node.type === 'table') {
        if (val.length > 0) {
          this.multipleSelection = val
          // console.log('nbbb', this.multipleSelection)
        }
      } else if (this.node.type === 'output') {
        this.multipleSelection = val
      }
    },
    // 分组,下拉值发生改变
    selectChange(val) {
      if (this.node.type === 'group' || this.node.type === 'order') {
        this.node.data.selectNodeId = this.node.data.nodeId[val]
        this.node.data.selectTableField = ''
      } else if (this.node.type === 'logic') {
        this.node.data.selectNodeId = this.node.data.nodeId[val]
        this.node.data.selectNodeField = ''
      }
    }
  }
}
</script>

<style>
.el-node-form-tag {
  position: absolute;
  top: 50%;
  margin-left: -15px;
  height: 40px;
  width: 15px;
  background-color: #fbfbfb;
  border: 1px solid rgb(220, 227, 232);
  border-right: none;
  z-index: 0;
}
</style>
